package com.zztl.infiniteBand.net.converter

import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.zztl.infiniteBand.model.BaseResponseBean
import java.lang.reflect.Type

/**
 * 转换数据
 * Created by yannable on 2018/1/31.
 */

class DataConverter private constructor(){

    //    private static Gson mGson = new GsonBuilder()
    //            .registerTypeAdapter(BaseResponseBean.class, new BaseResponseBeanGsonDeserializer())
    //            .create();
    private val mGson = Gson()


    //单例模式
    private object Holder{
        val INSTANCE=DataConverter()
    }

    companion object {
        val instance: DataConverter by lazy { Holder.INSTANCE }
    }
    /**
     * 为后台返回定制的.避免非成功状态时data类型错误
     */
    @Throws(JsonSyntaxException::class)
    public fun <T> getSingleBean(jsonData: String, clazz: Class<T>): T {
        val className = clazz.simpleName
        val SuperclassName = clazz.superclass.simpleName
        if (className == "BaseResponseBean" || SuperclassName == "BaseResponseBean") {
            val baseBean = mGson.fromJson(jsonData, BaseResponseBean::class.java)

            return mGson.fromJson(jsonData, clazz)

        } else {
            return mGson.fromJson(jsonData, clazz)
        }

    }

    /**
     * 正常情况
     *
     * @throws Exception
     */
    @Throws(JsonSyntaxException::class)
    fun <T> getSingleBean2(jsonData: String, clazz: Class<T>): T {
        return mGson.fromJson(jsonData, clazz)
    }

    /* public static <T> T getSingleBean(String jsonData, GenericType<T> genericType) throws JsonSyntaxException {
        return mGson.fromJson(jsonData, genericType.getType());
    }
*/
    @Throws(JsonSyntaxException::class)
    fun <T> getSingleBean(jsonData: String, type: Type): T {
        //        Type type = new TypeToken<BaseResponseBean<LoginBean>>() {
        //        }.getType();
        return mGson.fromJson(jsonData, type)
    }

    /**
     * 功能描述：Object对象转化成json数据
     */
    fun toJson(obj: Any): String {
        return mGson.toJson(obj)
    }



}
